<div class="container-fluid" id="nodeTable">
	<h4 class="c-grey-900 mT-10 mB-30" th:text="#{node.admin.tsa.title}"></h4>
	<div class="row">
		<div class="col-md-12">
			<div class="bgc-white bd bdrs-3 p-20 mB-20">
				<h4 class="c-grey-900 mB-20" th:text="#{table.node.tsa.title}"></h4>
				<table id="tableTsaNode" class="table table-striped table-bordered" 
					cellspacing="0" width="100%">
					<thead>
						<tr>
							<!-- Columna oculta para el identificador de la plataforma -->
							<th></th>
							<th th:text="#{table.node.name}"></th>
							<th></th>
							<th></th>
							<th></th>
							<th th:text="#{table.node.address}"></th>
							<th th:text="#{table.node.check.emergencydb}"></th>
							<th th:text="#{table.node.check.afirma}"></th>
							<th th:text="#{table.node.check.hsm}"></th>
						</tr>
					</thead>
				</table>
			</div>
		</div>
	</div>
</div>

<script th:inline="javascript">
$(document).ready(function() {
				
	var actionSave = /*[[@{/savetsanode}]]*/;
	var actionDelete = /*[[@{/deletenode}]]*/;
	var gettsas = /*[[@{/nodetsadatatable}]]*/;
	var editTemplate = /*[[@{/edittsanode}]]*/;
	var addTemplate = /*[[@{/addtsanode}]]*/;
	var tbl = $('#tableTsaNode').DataTable({
		dom: 'Bfrtip',
	    select: 'single',
	    responsive: true,
	    
	    altEditor: true,
	    buttons: [{text: 'Agregar',name: 'add'}, {extend: 'selected',text: 'Editar',name: 'edit'}, {extend: 'selected',text: 'Eliminar',name: 'delete'}],
	
	    "iTotalRecords": "totalElements",
        "iTotalDisplayRecords": "numberOfElements",
	    
		"processing": true,
	    "serverSide": true,
		"ajax": {
	        "url": gettsas,
	        "dataSrc" : "data",
	        "data": function (data) {
	        	// Datos a pasar al modal
	            data.formId = "nodeForm";
	            data.editTemplate = editTemplate;
	            data.addTemplate = addTemplate;
	        }
	      },
	    "language": {
	        "url": "js/datatables/i18n/spanish.json",
	        select: {
	            rows: {
	                _: "%d filas seleccionadas",
	                1: "1 fila seleccionada"
	            }
	          }
	        },
		"columns": [
	        { "data": "idNode",
	          "visible": false},
	        { "data": "name" },
	        { "data": "host",
	          "visible": false},
	        { "data": "port",
	          "visible": false},
	        { "data": "isSecure",
		      "visible": false},
	        { "data": "host",
	        	
	        	"render": function (data, type, row) {	
					
	        		if (data != null && data != '' && data != 'undefined') {
						var host = row.host;
						var port = row.port;
						var isSecure = row.isSecure;
						var protocol;
						var url;
						
						if (isSecure == true) {
							protocol = 'https';
						} else {
							protocol = 'http';
						}
						
						if (port == null || port == '' || port == 'undefined')
	        			{
	        				url = protocol + "://" + host;
	        			} else 
	        			{
	        				url = protocol + "://" + host + ":" + port;
	        			}
						
						
						return url;
	        		} else {
						return 'N/A';
					}
	        	}
	        
	        },
	        { "data": "checkEmergencyDB",
	          "render": function (data, type, row) {
	        	  
	        	var is_checked = data == true ? "checked" : "";
	        	  
	        	return '<div class="checkbox checkbox-circle checkbox-info peers ai-c"><input disabled type="checkbox" id="tableEmergencyDB" class="peer"' + is_checked + '><label for="tableEmergencyDB" class="peers peer-greed js-sb ai-c"><span class="peer peer-greed" ></span></label></div>';
	        		        	  
	          }		
	        },
	        { "data": "checkAfirma",
		      "render": function (data, type, row) {
		        	  
		    	  var is_checked = data == true ? "checked" : "";
			        	  
			      return '<div class="checkbox checkbox-circle checkbox-info peers ai-c"><input disabled type="checkbox" id="tableAfirma" class="peer"' + is_checked + '><label for="tableAfirma" class="peers peer-greed js-sb ai-c"><span class="peer peer-greed" ></span></label></div>';
				}
	        },
	        { "data": "checkHsm",
			  "render": function (data, type, row) {
		        	  
				 var is_checked = data == true ? "checked" : "";
				        	  
				 return '<div class="checkbox checkbox-circle checkbox-info peers ai-c"><input disabled type="checkbox" id="tableHsm" class="peer"' + is_checked + '><label for="tableHsm" class="peers peer-greed js-sb ai-c"><span class="peer peer-greed" ></span></label></div>';
				}
	        }
	        ]
		}).on('crudaction', function(e, accion, idNode, data, rowindex){
		    // e          Evento Jquery
		    // accion     [add|edit|delete]
		    // pkid       Primer campo en la data [id]                ... en add,    retorna null
		    // data       Los campos adicionales  [campo_1, campo_n]  ... en delete, retorna null
		    // rowindex   El index de la fila para el dataTable       ... en add,    retorna null
		    
		    $('#altEditor-modal .modal-body .alert').remove();
		    // Se muestra la capa 'cargando...'
		    loading();
		    
		    switch(accion){
		        case 'add':
		        	if ($('#nodeAfirmaForm')[0].checkValidity() === false) {
		        		// Se oculta la capa 'cargando...'
		        		hide();
		                event.stopPropagation();
		                
		                $('#nodeAfirmaForm *').filter(':input').each(function(){
		            	    		            	    
		            	    if(!$(this).checkValidity())
		            	    {
		            	  	 $("#invalid-" + $(this).attr('id')).html();
		            	  	 $("#" + $(this).attr('id')).addClass("is-invalid");
		            	    } else {
		            	  	 $("#" + $(this).attr('id')).removeClass("is-invalid");
		            	    }
		            	    
		            	});
		                
		                // Esto es necesario para forzar que se muestren mensajes de validacion de cliente
		                $('<input type="submit">').hide().appendTo($('#nodeAfirmaForm')).click().remove();
		            } else {
		            	$.ajax(actionSave, {
			            	dataType : 'json',
			            	contentType:'application/json',
			                data : JSON.stringify(data),
			                type:'POST',
			                success: function(data){
			                  
								var errores = JSON.parse(data.error);
								
								if (data.error != null){
									  jQuery.each(errores, function(i, val) {
										$('#nodeAfirmaForm *').filter('.invalid-modal').each(function(){

											if (i == $(this).attr('id')){
												$("#" + i).text(val);
											}
										});
									  });
								  }else{
									//tbl.row.add($(data.data)).draw(false);
									// Es necesario invalidar los datos para actualizar los campos check
									$('#tableTsaNode').DataTable().rows().invalidate('data').draw(false);
									
									$('#altEditor-modal .modal-body .alert').remove();
				                    $('#altEditor-modal').modal('hide');
								  }
			                	
			            		// Se oculta la capa 'cargando...'
			            		hide();
			                    
			                    if ($('#errorModalNode').length > 0){
									$('#errorModalNode').remove();
								}
			                    
			                },
			                error:function(data){
			                	hide();
			                	$('#nodeAfirmaForm').append('<div id="errorModalNode" class="alert alert-danger" role="alert"><strong>' + [[#{node.admin.error.sameName}]] + '</strong></div>');
			                }
			            });
		            }
		        	$('#nodeAfirmaForm').addClass('was-validated');
		            break;
		        case 'edit':
		        	if ($('#nodeAfirmaForm')[0].checkValidity() === false) {
		        		// Se oculta la capa 'cargando...'
		        		hide();
		                event.stopPropagation();
		                
		                $('#nodeAfirmaForm *').filter(':input').each(function(){
		            	    		            	    
		            	    if(!$(this).checkValidity())
		            	    {
		            	  	 $("#invalid-" + $(this).attr('id')).html();
		            	  	 $("#" + $(this).attr('id')).addClass("is-invalid");
		            	    } else {
		            	  	 $("#" + $(this).attr('id')).removeClass("is-invalid");
		            	    }
		            	    
		            	});
		                
		                // Esto es necesario para forzar que se muestren mensajes de validación de cliente
		                $('<input type="submit">').hide().appendTo($('#nodeAfirmaForm')).click().remove();
		            } else {
		            	$.ajax(actionSave, {
			            	dataType : 'json',
			            	contentType:'application/json',
			                data : JSON.stringify(data),
			                type:'POST',
			                success: function(data){
			                  
			            		// Se oculta la capa 'cargando...'
			            		hide();
			                    //tbl.row.add($(data.data)).draw(false);
			                    $('#tableTsaNode').DataTable().rows().invalidate('data').draw(false);
			                    		                    
			                    $('#altEditor-modal .modal-body .alert').remove();
			                    $('#altEditor-modal').modal('hide');
			                    
			                    if ($('#errorModalNode').length > 0){
									$('#errorModalNode').remove();
								}
			                },
			                error:function(data){
			                	hide();
			                	$('#nodeAfirmaForm').append('<div id="errorModalNode" class="alert alert-danger" role="alert"><strong>' + [[#{node.admin.error.sameName}]] + '</strong></div>');
			                }
			            });
		            }
		        	$('#nodeAfirmaForm').addClass('was-validated');
	            	break;
		        case 'delete':
		            $.ajax(actionDelete,{
		            	data:$.param({'id':idNode, 'index':rowindex}),
		                type:'POST',
		                success: function(data){
		                    
		                	if (data == "-1" && $('#errorNode').length == 0){
		                		$('#tableTsaNode').append('<div id="errorNode" class="alert alert-danger" role="alert"><strong>' + [[#{node.admin.error.inUse}]] + '</strong></div>');
		                	}else{
								$('#errorNode').remove();
							}
		                	
		                	// Se oculta la capa 'cargando...'
		                	hide();
		                    //tbl.row(data.index).remove().draw();
		                    $('#tableTsaNode').DataTable().rows().invalidate('data').draw(false);
		                    
		                    $('#altEditor-modal .modal-body .alert').remove();
		                    $('#altEditor-modal').modal('hide');
		                },
		                error:function(){}
		            });
		            break;
		        default:
		            $('#altEditor-modal .modal-body .alert').remove();
		            $('#altEditor-modal .modal-body').append('<div class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.NotAuthorized}]] + '</strong></div>');
		            break;
		    }
		});
});	

</script>